<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\Exception;
use think\facade\Filesystem;
use think\facade\Log;
use think\Event;
use app\event\AssetHistoriesEvent;

class AssetsStockin extends BaseController
{
    //查询所有基础资料
    public function get_AllBasis()
    {

        $userId = $this->request->auth['data']->user->user_id;
        $userRoot = $this->request->auth['data']->user->user_root;

        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = [];

        //查询所有部门信息
        $data['branch']=Db::table('branch')->where('branch_company_id', $companyId)->select();
        $data['department'] = Db::table('department')->where('department_company_id', $companyId)->where('department_switch', 1)->select();
        $data['location'] = Db::table('location')->where('location_company_id', $companyId)->where('location_switch', 1)->select();
        $data['supplier'] = Db::table('supplier')->where('supplier_company_id', $companyId)->where('supplier_switch', 1)->select();
        $data['customer'] = Db::table('customer')->where('customer_company_id', $companyId)->where('customer_switch', 1)->select();
        $data['AssetTypes'] = getAssetTypesTree($companyId);

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $data
        ]);


    }

    //查询所有资产入库单及其明细
    public function get_AllAssetsStockinList()
    {

        $userRoot = $this->request->auth['data']->user->user_root;
        $userId = $this->request->auth['data']->user->user_id;


        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $current_page = Request::param('current_page');
        $page_size = Request::param('page_size');
        $begindate = Request::param('begindate'); // 开始日期
        $enddate = Request::param('enddate'); // 结束日期
        $billnumber = Request::param('billnumber'); // 订单号
        $state = Request::param('state');//审核状态
        $branch=Request::param('branch');//区域

        // 构建查询条件
        $where = [];

        if ($begindate && $enddate) {
            // 设置开始日期的时分秒为00:00:00
            $startOfDay = date('Y-m-d 00:00:00', strtotime($begindate));
            // 设置结束日期的时分秒为23:59:59（或者你也可以选择结束日期的次日00:00:00来简化比较）
            $endOfDay = date('Y-m-d 23:59:59', strtotime($enddate));

            // 使用范围查询
            $where[] = ['instock_creationtime', '>=', $startOfDay];
            $where[] = ['instock_creationtime', '<=', $endOfDay];
        }

        if ($billnumber) {
            $where[] = ['instock_BillNumber', 'like', '%' . $billnumber . '%'];

        }
        if ($companyId) {
            $where['instock_company_id'] = $companyId;
        }
        if ($state) {
            $where['instock_state'] = $state;
        }
        if ($branch) {
            $where['instock_branch_id'] = $branch;
        }


        // 查询主表数据,按照PurchaseBill_creationtime时间字段排序
        $mainList = Db::table('vw_instock')
            ->where($where)
            ->where('instock_deleted', 0)
            ->order('instock_creationtime', 'desc')//按时间降序排名
            ->page($current_page, $page_size)
            ->select()->toarray();


        // 遍历主表数据，查询并附加明细表数据
        $data = [];

     
        foreach ($mainList as &$item) {
            // 查询对应的明细表数据
            $detailList = Db::table('vw_instock_assets')
                ->where('assets_instock_id', $item['instock_id'])
                ->select();

            // 将明细表数据附加到主表数据上
            $item['detail'] = $detailList;
        }

        unset($item); // 取消引用，避免后续对$item的修改影响到$mainList


        // 获取总记录数
        $totalCount = Db::table('instock')
            ->where($where)
            ->where('instock_deleted', 0)
            ->order('instock_creationtime', 'desc')//按时间降序排名
            ->count();


        // 返回JSON数据
        return json([
            'code' => 200, // 自定义状态码，0表示成功
            'msg' => '查询成功', // 自定义消息
            'data' => [
                'data' => $mainList, // 主表数组包含明细表数组
                'total' => $totalCount, // 总数量

            ]

        ]);


    }

    //添加资产入库单
    public function add_AssetsStockin()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');


        try {
            // 开启事务
            Db::startTrans();
            // 生成进货单号
            $instockBillNo = generateOrderNumber($companyId,'JH','instock');

            // 获取请求中的主表数据和资产明细数据
            $instock = Request::param('instock');
            $assets = filterEmptyValues(Request::param('assets'));

            $instock['instock_company_id'] = $companyId;
            $instock['instock_BillNumber'] = $instockBillNo;
            $instock['instock_state'] = '未审核';
            $instock['instock_quantity'] = count(Request::param('assets'));
            $instock['instock_user_id'] = $userId;

            $instockId = Db::table('instock')->insertGetId($instock);

            if (!$instockId) {
                throw new \Exception('添加进货单主记录失败');
            }

            // 遍历货品明细并添加记录
            foreach ($assets as $detail) {
                // 生成条码（这里假设有一个generateBarcode函数）
                $barcode = generateBarcode($companyId);

                $DetailBill = $detail;
                $DetailBill['assets_code'] = $barcode;
                $DetailBill['assets_company_id'] = $companyId;
                $DetailBill['assets_instock_id'] = $instockId;
                $DetailBill['assets_InputStatus'] = '未审核';
                $DetailBill['assets_branch_id'] = $instock['instock_branch_id'];
                $result = Db::table('assets')->insert($DetailBill);
                if (!$result) {
                    throw new \Exception('添加进货单明细记录失败');
                }
            }

            // 提交事务
            Db::commit();

            // 添加成功，返回响应
            return json(['code' => '200', 'msg' => '进货单添加成功']);


        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['code' => '402', 'msg' => $e->getMessage()]);


        }
    }

    //修改资产入库单
    public function update_StockinDetail()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        Db::startTrans();
        try {
            $purchaseDetailBillId =Request::param('assets_id');
            $data = Request::param('data');

            // 定义要忽略的字段列表
            $ignoredFields = [
                'assets_AssetTypes_name',
                'assets_code',
                'assets_ImageURL',
                'assets_InputStatus',
                'assets_company_id',
                'assets_creationtime',
                'assets_customer_name',
                'assets_department_name',
                'assets_location_name',
                'assets_quantity',
                'assets_supplier_name',
                'assets_instock_id',
                'assets_id',
            ];


            if(empty($data)){
                throw new \Exception('修改数据不能为空');
            }
            if(empty($purchaseDetailBillId)){
                throw new \Exception('进货单明细ID不能为空');
            }else{
                $data = array_diff_key($data, array_flip($ignoredFields));
                $updateResult = Db::table('assets')
                    ->where('assets_id', $purchaseDetailBillId)
                    ->update($data);
                if (!$updateResult) {
                    throw new \Exception('更新进货单明细信息失败');
                }else{

                    Db::commit();
                    //根据PurchaseDetailBill_id查询PurchaseBill_id,获取PurchaseBill_id,再根据PurchaseBill_id查询PurchaseDetailBill表中对应的数据
                    $PurchaseBill_id = Db::table('assets')
                        ->where('assets_id', $purchaseDetailBillId)
                        ->value('assets_instock_id');
                    $PurchaseDetailBill = Db::table('vw_instock_assets')
                        ->where('assets_instock_id', $PurchaseBill_id)
                        ->select();
                    //返回更新成功信息
                }
            }
            return json(['code' => 200,'msg' => '更新成功','data'=>$PurchaseDetailBill]);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    //修改入库单主表
    public function update_Stockin()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        Db::startTrans();
        try {
            $purchaseBillId =Request::param('instock_id');
            
            $data = Request::param('data');
            if(empty($data)){
                throw new \Exception('修改数据不能为空');
            }else{
                $updateResult = Db::table('instock')
                    ->where('instock_id', $purchaseBillId)
                    ->update($data);
                if (!$updateResult) {
                    throw new \Exception('更新进货单信息失败');
                }else{
                    Db::commit();
                    //返回更新成功信息
                    return json(['code' => 200,'msg' => '更新成功']);
                }
            }

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    //审核入库单
    public function check_Stockin()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        try {
            $instockId =Request::param('instock_id');
            //开启事务
            Db::startTrans();
            if(empty($instockId)){
                throw new \Exception('入库单ID不能为空');
            }else{
                //审核单据
                $result = Db::table('instock')
                    ->where('instock_id', $instockId)
                    ->update(['instock_state' => '已审核']);
                if (!$result) {
                    throw new \Exception('审核单据失败');
                }else{
                    //审核明细
                    $result = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->update(['assets_InputStatus' => '已审核']);
                    //将所有已审核的资产记录在资产历史记录表中
                    $assetsAll = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->where('assets_InputStatus', '已审核')
                        ->select()->toArray();
//                    foreach ($assetsAll as $key => $value) {
//                        $data = [
//                            'AssetHistories_assets_id' => $value['assets_id'],
//                            'AssetHistories_type' => '入库',
//                            'AssetHistories_bill_id' => $instockId,
//                            'AssetHistories_user_id' =>$userId,
//                            'AssetHistories_company_id' => $companyId,
//                            ];
//                        if(!empty($value['assets_id'])){
//                            $result1 = Db::table('AssetHistories')
//                                ->insert($data);
//                        }
//                        }
                    //使用事件触发器
                    event(new AssetHistoriesEvent($instockId, $assetsAll, $userId, $companyId,'入库'));

                    if (!$result) {
                        throw new \Exception('审核明细失败');
                    }else{
                        Db::commit();
                        //返回审核成功信息
                        return json(['code' => 200,'msg' => '审核成功']);
                    }
                }

            }


        }
        catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }



    }

    //作废入库单
    public function invalid_Stockin()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        try {
            $instockId =Request::param('instock_id');
            //开启事务
            Db::startTrans();
            if(empty($instockId)){
                throw new \Exception('入库单ID不能为空');
            }else{
                $result = Db::table('instock')
                    ->where('instock_id', $instockId)
                    ->update(['instock_state' => '已作废']);
                if (!$result) {
                    throw new \Exception('作废单据失败');
                }else{
                    //审核明细
                    $result = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->update(['assets_InputStatus' => '已作废']);
                    if (!$result) {
                        throw new \Exception('作废明细失败');
                    }else{
                        Db::commit();
                        //返回审核成功信息
                       return json([
                               'code' => 200,
                               'msg' => '作废成功'
                           ]);
                    }

                 }

            }

        }
        catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }



    }

    //删除入库单
    public function delete_Stockin()
    {
        $userId = $this->request->auth['data']->user->user_id;
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');
        try {
            $instockId =Request::param('instock_id');
            //开启事务
            Db::startTrans();
            if(empty($instockId)){
                throw new \Exception('入库单ID不能为空');
            }else{
                $result = Db::table('instock')
                    ->where('instock_id', $instockId)
                    ->delete();
                if (!$result) {
                    throw new \Exception('删除单据失败');
                }else{
                    //根据$instockId找查出所有的assets_code
                    $assetsCode = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->column('assets_code');
                    //删除对应的图片,图片目录在public/uploads/$companyId,图片名称为assetsCode
                    if (!empty($assetsCode)) {
                        // 遍历图片代码，尝试删除每个文件
                        foreach ($assetsCode as $value) {
                            // 使用public_path()获取public目录的绝对路径
                            $filePath ='/www/wwwroot/tp6erp/public/uploads/' . $companyId . '/' . $value.'.*';

                            //unlink('/www/wwwroot/tp6erp/public/uploads/2/200000004.jpeg');
                            $files = glob($filePath);
//                            foreach ($files as $file)
//                            {
//                                unlink($file);
//                            }

                            if($files)
                            {
                                foreach ($files as $file) {
                                    if (file_exists($file)) {
                                        // 尝试删除文件
                                        if (unlink($file)) {
                                            // 成功删除，记录日志
                                            Log::info("File deleted: {$file}");
                                        } else {
                                            // 删除失败，记录错误日志
                                            Log::error("Failed to delete file: {$file}");
                                        }
                                    } else {
                                        // 虽然glob返回了这个文件，但实际上它不存在（可能是同时被其他进程删除），记录警告日志
                                        Log::warning("File not found (even though glob returned it): {$file}");
                                    }
                                   }
                                }else {
                                // 没有找到匹配的文件，记录警告日志
                                Log::warning("No files found matching pattern: {$filePath}");
                            }

//                            // 检查文件是否存在
//                            if (file_exists($filePath)) {
//                                // 尝试删除文件
//                                if (unlink($filePath)) {
//                                    // 成功删除，可以在这里添加日志或成功提示
//                                    Log::record("File deleted: {$filePath}", 'info');
//                                } else {
//                                    // 删除失败，记录错误日志
//                                    Log::error("Failed to delete file: {$filePath}");
//                                }
//                            } else {
//                                // 文件不存在，记录警告日志
//                                Log::warning("File not found: {$filePath}");
//                            }
                        }

                        // 根据需要返回操作结果给前端或进行其他处理

                    } else {
                        // 如果$assetsCode为空，则记录警告并返回相应信息
                        Log::warning("No assetsCode found to delete.");

                    }
                    //审核明细
                    $result = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->delete();
                    if (!$result) {
                        throw new \Exception('删除明细失败');
                    }


                }
                Db::commit();
            }
            return json(['code' => 200,'msg' => '删除成功']);

        }
        catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }



    }

    //导入excel时检查基础资料
    public function checkImportData()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = Request::param('data');

        $fieldsToCheck = [
            '资产类别' => 'AssetTypes',
            '责任部门' => 'department', // 假设存在这个表
            '使用人' => 'customer',
            '存放位置' => 'location',// 假设存在这个表
            '供应商' => 'supplier', // 假设存在这个表

        ];

        $uniqueMissingData = []; // 用于存储去重后的缺失数据
        $missingData = []; // 用于存储缺失的基础数据的数组


        $count = 0;
        foreach ($data as $item) {
            $count++;
            foreach ($fieldsToCheck as $field => $table) {
                if (isset($item[$field])) {
                    $value = $item[$field];
                    //检查AssetTypes是否是最底层的层级
                    if($table == 'AssetTypes'){
                        $AssetTypesId = Db::table('AssetTypes')->where('AssetTypes_name', $value)->where('AssetTypes_company_id',$companyId)->value('AssetTypes_id');
                        if($AssetTypesId){
                            $pareninfo=Db::table('AssetTypes')->where('AssetTypes_parentid',$AssetTypesId)->find();
                            if($pareninfo){
                                return json(['code' => 500, 'msg' => '资产类别填写错误，请检查第'.($count+7).'行！']);
                            }

                        }

                    }
                    $exist = Db::table($table)->where($table.'_name', $value)->where($table.'_company_id',$companyId)->find();
                    if (!$exist) {
                        $missingData[] = ['field' => $field,'table' => $table, 'value' => $value];

                    }

                    // $checkedItems[] = $field;
                }
            }

        }
//        var_dump($data);


        foreach ($missingData as $item) {
            // 根据field、value和table生成唯一键
            $uniqueKey = $item['field'] . '_' . $item['value'] . '_' . $item['table'];


            $exists = false;

            foreach ($uniqueMissingData as $existingItem) {
                // 如果存在相同值的“石头类别”，则跳过当前项

                // 检查是否已存在相同的唯一键（排除“石头类别”项）
                if ($existingItem['unique_key'] === $uniqueKey) {
                    $exists = true;
                    break;
                }
            }



            if (!$exists) {
                // 添加 unique_key 到每个项中以用于去重
                $item['unique_key'] = $uniqueKey;

                // 将项添加到$uniqueMissingData数组中
                $uniqueMissingData[] = $item;

            }


        }

        // 去除 unique_key，如果不需要在结果中保留
        foreach ($uniqueMissingData as &$item) {
            unset($item['unique_key']);
        }

        return json(['code'=>200,'msg'=>'success','data' => $uniqueMissingData]);







    }

    //新增基础资料
    public function addBaseData()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = Request::post('data'); // 假设前端发送的是POST请求，且数据在'data'字段中，格式为JSON

        // 开启事务
        Db::startTrans();
        try {
            foreach ($data as $item) {
                $tableName = $item['table'];
                $fieldName = $tableName. '_name';
                $fieldCompany= $tableName. '_company_id';
                $fieldSwitch = $tableName. '_switch';
                $fieldValue = $item['value'];

                // 检查字段是否已存在
                $isFieldExist = Db::table($tableName)->where($fieldName, $fieldValue)->where($fieldCompany,$companyId)->find();
                if (!$isFieldExist) {
                    // 字段不存在，则添加新记录
                    $result = Db::table($tableName)->insert([
                        $fieldName => $fieldValue,
                        $fieldCompany => $companyId,
                        $fieldSwitch => 1
                    ]);

                    if (!$result) {
                        throw new Exception('添加字段失败');
                    }
                }
            }

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code' => 200, 'msg' => '添加字段成功']);
        } catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }



    }

    //根据前端传回的数据,找查相应的id
    public function getIdByFieldAndValue()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $data = Request::post('data'); // 假设前端发送的是POST请求，且数据在'data'字段中，格式为JSON

        $result = [];

        foreach ($data as $item) {
            $newItem = [];

            // 遍历每个字段
            foreach ($item as $key => $value) {
                if ($key === 'assets_name') {
                    // assets_name 字段不需要处理，直接保留
                    $newItem[$key] = $value;

                }  else if (strpos($key, '_name') !== false) {
                    // 移除 PurchaseDetailBill_ 前缀和 _name 后缀，并替换为 SET_
                    $dbName = str_replace(['assets_', '_name'],['',''], $key);


                    // 查询 ID
                    $id = Db::table($dbName)->where($dbName.'_name', $value)->where( $dbName . '_company_id', $companyId)->value($dbName . '_id');

                    // 如果没有找到 ID，则向前端返回 JSON 并终止处理
                    if (!$id) {
                        return json(['code'=>201,'msg' => "没有找到对应的ID: " . $key, 'data' => null], 201);
                    }

                    // 替换 _name 为 _id 并设置值
                    $newItem[str_replace('_name', '_id', $key)] = $id;
                } else {
                    // 不带 _name 的字段直接保留
                    $newItem[$key] = $value;
                }
            }

            // 添加到结果数组中
            $result[] = $newItem;
        }

        // 返回处理后的数组给前端
        return json(['code'=>200,'data' => $result], 200);

    }

    //删除入库单中的资产
    public function delete_StockAssets()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        Db::startTrans();
        try {
            // 获取前端传来的资产id
            $assets_id = Request::param('assets_id');
//            //删除资产
//            $result = Db::table('assets')->where('assets_id', $assets_id)->delete();

            //找查所属的入库单id
            $assets_list=[];
            $instock_id=Db::table('assets')->where('assets_id', $assets_id)->value('assets_instock_id');
            //删除资产前先查找入库单里的资产是否小于1个，如果小于等于1个则删除资产的同时删除入库单
            $assets_count=Db::table('assets')->where('assets_instock_id', $instock_id)->count();
            if($assets_count<=1){
                //删除入库单
                $result = Db::table('instock')->where('instock_id', $instock_id)->delete();
                //删除资产
                $result = Db::table('assets')->where('assets_id', $assets_id)->delete();
            }else{
                //删除资产
                $result = Db::table('assets')->where('assets_id', $assets_id)->delete();
                //返回此入库单所有资产
                $assets_list=Db::table('assets')->where('assets_instock_id', $instock_id)->select();
            }
            if($result){
                // 提交事务
                Db::commit();
                return json(['code'=>200,'msg' => '删除成功','data'=>$assets_list]);
            }else{
                // 回滚事务
                Db::rollback();
                return json(['code'=>201,'msg' => '删除失败']);
            }


        }
        catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>201,'msg' => $e->getMessage()]);
        }

    }

    //反审核入库单
    public function uncheck_StockIn()
    {
        $userRoot = $this->request->auth['data']->user->user_root;
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        try {
            Db::startTrans();
            //先检查入库单下的资产的状态
            $instockId =Request::param('instock_id');

            $instock_one = Db::table('instock')
                ->where('instock_id', $instockId)
                ->find();
            //获取此入库单下所有的资产
            $assets_list = Db::table('assets')
                ->where('assets_instock_id', $instockId)
                ->select()->toArray();
            //获取所有资产id
            $assets_id_list = array_column($assets_list, 'assets_id');

            $AssetHistories_date = Db::table('AssetHistories')
                ->where('AssetHistories_bill_id', $instockId)
                ->where('AssetHistories_assets_id', 'in', $assets_id_list)
                ->where('AssetHistories_type','入库')
                ->order('AssetHistories_date', 'desc')
                ->value('AssetHistories_date');

            if($instock_one['instock_state']=='已审核'){

                $AssetHistories_date_one = Db::table('AssetHistories')
                    ->where('AssetHistories_bill_id', '<>', $instockId)
                    ->where('AssetHistories_assets_id', 'in', $assets_id_list)
                    ->where('AssetHistories_date', '>', $AssetHistories_date)
                    ->find();
                if ($AssetHistories_date_one) {
                    //json返回是哪个资产,拼接返回显示资产编号资产名称
                    $Asset_one = Db::table('assets')
                        ->where('assets_id', $AssetHistories_date_one['AssetHistories_assets_id'])
                        ->find();
                    $Asset_name = $Asset_one['assets_name'];
                    $Asset_number = $Asset_one['assets_code'];
                    return json([
                        'code' => 500,
                        'msg' => '资产:'.$Asset_name.' 编号:'.$Asset_number.' 已产生了'.$AssetHistories_date_one['AssetHistories_type'].'单据,单据号:'.getBillNumber($AssetHistories_date_one['AssetHistories_type'],$AssetHistories_date_one['AssetHistories_bill_id']).'请先处理此单据',
                        'data' => [
                            'Asset_name' => $Asset_name,
                            'Asset_number' => $Asset_number
                                  ]
                                 ]);

                }else{
                    //反审核单据
                    //修改入库单状态为未审核
                    $result = Db::table('instock')
                        ->where('instock_id', $instockId)
                        ->update(['instock_state' => '未审核']);
                    //修改此单据下所有资产状态为未审核
                    $result = Db::table('assets')
                        ->where('assets_instock_id', $instockId)
                        ->update(['assets_InputStatus' => '未审核']);
                    //删除此入库单下的资产历史记录
                    $result = Db::table('AssetHistories')
                        ->where('AssetHistories_bill_id', $instockId)
                        ->where('AssetHistories_type','入库')
                        ->delete();
                    if($result){
                        // 提交事务
                        Db::commit();
                        return json(['code'=>200,'msg' => '反审核成功']);
                    }else{
                        // 回滚事务
                        Db::rollback();
                        return json(['code'=>201,'msg' => '反审核失败']);
                    }

                }

            }

        }
        catch (\Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }






    }







}